// 为主页创建流动的烟雾效果
document.addEventListener('DOMContentLoaded', function() {
  if (!document.getElementById('smoke-canvas')) return;
  
  const canvas = document.getElementById('smoke-canvas');
  const ctx = canvas.getContext('2d');
  
  // 设置canvas尺寸为窗口大小
  const resizeCanvas = () => {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
  };
  
  window.addEventListener('resize', resizeCanvas);
  resizeCanvas();
  
  // 烟雾粒子类 - 设计为飘渺的香烟烟气，一缕一缕的
  class SmokeParticle {
    constructor(x, y) {
      this.reset();
      // 设置起始位置 - 更分散，创造自然的烟气起源点
      this.x = x || (Math.random() * canvas.width * 0.8) + (canvas.width * 0.1); // 分散在画布上
      this.y = y || canvas.height + Math.random() * 30;
      this.initialX = this.x; 
    }
    
    update() {
      // 向上飘动
      this.y += this.speedY;
      this.life -= 0.12; // 更慢的消失速度，让烟气存在更久
      
      // 随高度增加漂移 - 模拟真实烟气缓慢扩散和飘荡的效果
      const heightFactor = (canvas.height - this.y) / canvas.height;
      this.x = this.initialX + (Math.sin(this.y * 0.002 + this.seed) * this.swayStrength * heightFactor);
      
      // 随高度增加透明度，使烟气变得更飘渺
      const opacityFactor = Math.min(1, heightFactor * 2);
      this.opacity = Math.max(0, Math.min(this.maxOpacity * opacityFactor, (this.life / this.maxLife) * this.maxOpacity));
      
      // 控制旋转 - 随高度增加旋转速度，模拟空气扰动
      this.rotation += this.rotationSpeed * (1 + heightFactor * 0.5);
      
      // 随高度略微增加宽度，模拟扩散
      this.width = this.baseWidth + (heightFactor * 1.5);
      
      if (this.life <= 0) {
        this.reset();
      }
    }
    
    reset() {
      // 随机化参数 - 更多变化
      this.initialX = Math.random() * canvas.width; // 分散在整个画布上
      this.x = this.initialX;
      this.y = canvas.height + Math.random() * 30;
      
      // 烟气形状参数 - 更细长优雅的烟气
      this.baseWidth = Math.random() * 0.8 + 0.2; // 更窄的基础宽度，更像一缕烟
      this.width = this.baseWidth;
      this.height = Math.random() * 100 + 60; // 更长的高度，形成细长的烟雾
      
      // 速度与移动参数
      this.speedY = -Math.random() * 0.4 - 0.1; // 更慢的上升速度，更优雅
      this.seed = Math.random() * 10;
      this.swayStrength = Math.random() * 15 + 3; // 适度的漂移幅度
      
      // 生命周期 - 烟气持续更久
      this.life = Math.random() * 350 + 250;
      this.maxLife = this.life;
      this.maxOpacity = Math.random() * 0.05 + 0.01; // 更低的透明度，更飘渺
      this.opacity = 0; // 开始时完全透明，逐渐显现
      
      // 旋转参数 - 更慢的旋转，更优雅
      this.rotation = Math.random() * Math.PI * 2;
      this.rotationSpeed = (Math.random() - 0.5) * 0.003;
      
      // 烟雾颜色 - 更加柔和的白色和淡蓝色
      const colors = [
        [255, 255, 255], // 纯白
        [250, 250, 255], // 带一丝蓝的白
        [245, 245, 250], // 淡淡的蓝白
        [240, 240, 245]  // 更淡的蓝白
      ];
      this.color = colors[Math.floor(Math.random() * colors.length)];
      
      // 控制点偏移量 - 用于贝塞尔曲线
      this.ctrlPointVariation = Math.random() * 0.5 + 0.2;
    }
    
    draw() {
      ctx.save();
      
      // 移动到粒子位置并应用旋转
      ctx.translate(this.x, this.y);
      ctx.rotate(this.rotation);
      
      // 创建垂直渐变，使烟气看起来更自然
      const gradient = ctx.createLinearGradient(0, this.height/2, 0, -this.height/2);
      const [r, g, b] = this.color;
      
      // 更自然的渐变
      gradient.addColorStop(0, `rgba(${r}, ${g}, ${b}, 0)`);
      gradient.addColorStop(0.2, `rgba(${r}, ${g}, ${b}, ${this.opacity * 0.1})`);
      gradient.addColorStop(0.5, `rgba(${r}, ${g}, ${b}, ${this.opacity})`);
      gradient.addColorStop(0.8, `rgba(${r}, ${g}, ${b}, ${this.opacity * 0.1})`);
      gradient.addColorStop(1, `rgba(${r}, ${g}, ${b}, 0)`);
      
      // 绘制更优雅的烟气形状
      ctx.fillStyle = gradient;
      
      // 使用更简单的贝塞尔曲线创建一缕缕的烟气形状
      ctx.beginPath();
      const halfWidth = this.width / 2;
      
      // 控制点偏移
      const variation = this.ctrlPointVariation;
      
      // 从底部开始绘制
      ctx.moveTo(-halfWidth * 0.2, this.height/2);
      
      // 创建更细长的烟气形状
      ctx.bezierCurveTo(
        -halfWidth, this.height/4,
        -halfWidth * variation, -this.height/4,
        0, -this.height/2
      );
      
      ctx.bezierCurveTo(
        halfWidth * variation, -this.height/4,
        halfWidth, this.height/4,
        halfWidth * 0.2, this.height/2
      );
      
      ctx.closePath();
      ctx.fill();
      
      ctx.restore();
    }
  }
  
  // 创建更少的粒子，使烟雾效果更疏松
  const particles = [];
  const particleCount = 8; // 减少粒子数量，使效果更疏松
  
  for (let i = 0; i < particleCount; i++) {
    // 随机分布在画布底部
    const xPos = Math.random() * canvas.width;
    // 延迟出现，不要一次性全部显示
    setTimeout(() => {
      particles.push(new SmokeParticle(
        xPos,
        canvas.height + Math.random() * canvas.height * 0.05
      ));
    }, i * 500); // 每500毫秒添加一个粒子
  }
  
  // 动画循环
  function animate() {
    // 使用透明度清除画布来创建更长的拖尾效果
    ctx.fillStyle = 'rgba(2, 6, 23, 0.01)'; // 降低透明度，让烟气留存更久
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // 更新并绘制所有粒子
    particles.forEach(particle => {
      particle.update();
      particle.draw();
    });
    
    // 偶尔添加新的烟气粒子
    if (Math.random() < 0.005 && particles.length < 12) {
      particles.push(new SmokeParticle(
        Math.random() * canvas.width,
        canvas.height + Math.random() * 10
      ));
    }
    
    // 循环动画
    requestAnimationFrame(animate);
  }
  
  // 开始动画
  animate();
});

// 添加鼠标光晕效果 - 仅在鼠标悬停在可交互元素上时显示
document.addEventListener('DOMContentLoaded', function() {
  const cursor = document.createElement('div');
  cursor.classList.add('cursor-glow');
  cursor.style.opacity = '0';
  document.body.appendChild(cursor);
  
  // 更新光晕位置
  document.addEventListener('mousemove', (e) => {
    cursor.style.left = `${e.clientX}px`;
    cursor.style.top = `${e.clientY}px`;
  });
  
  // 在可交互元素上增强光晕效果
  const interactiveElements = document.querySelectorAll('a, button, .blog-card, .glass-hover');
  
  interactiveElements.forEach(el => {
    el.addEventListener('mouseenter', () => {
      cursor.style.opacity = '1';
      cursor.classList.add('cursor-glow-active');
    });
    
    el.addEventListener('mouseleave', () => {
      cursor.style.opacity = '0';
      cursor.classList.remove('cursor-glow-active');
    });
  });
});

// --- Simpler Green Leaf Animation (Rewritten) ---
document.addEventListener('DOMContentLoaded', function() {
  // console.log('【简单绿叶动画】初始化...');

  const leafContainer = document.createElement('div');
  leafContainer.id = 'green-leaf-container';
  leafContainer.style.cssText = `
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;
    z-index: 1; /* Positioned above absolute base, below content/effects */
    overflow: hidden;
    /* opacity: 1; // Default is 1, so explicit set not strictly needed if not overriding elsewhere */
  `;
  document.body.appendChild(leafContainer);

  const styleSheet = document.createElement('style');
  styleSheet.textContent = `
    .green-leaf {
      position: absolute;
      width: 20px;
      height: 30px;
      background-color: #4CAF50; /* Default green */
      border-radius: 30% 70% 40% 60% / 50% 50% 50% 50%; /* Basic leaf shape */
      filter: drop-shadow(0 1px 1px rgba(0,0,0,0.1));
      opacity: 0; /* Start transparent, fade in via JS animation */
      transform-origin: center bottom;
      will-change: transform, opacity; /* Restore will-change for performance */
    }
  `;
  document.head.appendChild(styleSheet);

  const maxLeaves = 3; // Reduced: Maximum number of leaves on screen
  const newLeafInterval = 5000; // Increased: Create a new leaf every 5 seconds (average)

  function createLeaf() {
    if (leafContainer.childElementCount >= maxLeaves) {
      return;
    }

    const leaf = document.createElement('div');
    leaf.className = 'green-leaf';

    const greenShades = ['#4CAF50', '#66BB6A', '#388E3C', '#81C784'];
    leaf.style.backgroundColor = greenShades[Math.floor(Math.random() * greenShades.length)];

    const size = 15 + Math.random() * 10; // 15px to 25px wide (slightly smaller max)
    leaf.style.width = `${size}px`;
    leaf.style.height = `${size * 1.5}px`;

    // Starting position: From top-right
    const startX = window.innerWidth * (0.6 + Math.random() * 0.4); // Start 60% to 100% from left
    const startY = -50 - Math.random() * 50; 
    leaf.style.left = `${startX}px`;
    leaf.style.top = `${startY}px`;

    // Animation parameters
    const duration = 18000 + Math.random() * 10000; // 18-28 seconds fall time (even slower avg)
    // Horizontal Drift: Consistently to the left
    const baseHorizontalDrift = - (window.innerWidth * 0.3 + Math.random() * window.innerWidth * 0.4); // Drift 30% to 70% of screen width to the left
    const endX = startX + baseHorizontalDrift;

    const initialRotation = Math.random() * 30 - 15; // Slight initial tilt (-15 to +15 deg)
    const rotationAmount = (Math.random() > 0.5 ? 1 : -1) * (30 + Math.random() * 60); // Total rotation during fall (+/- 30 to 90 deg)

    leaf.style.transform = `rotate(${initialRotation}deg)`;
    leafContainer.appendChild(leaf);

    let startTime = null;

    function animate(timestamp) {
      if (!startTime) startTime = timestamp;
      const progress = Math.min(1, (timestamp - startTime) / duration);

      const currentY = startY + (window.innerHeight + 100) * Math.pow(progress, 1.1); // Slower fall with Math.pow exponent 1.1
      
      // Horizontal movement: Smooth drift from startX towards endX
      const currentX = startX + (endX - startX) * progress;
      const currentRotation = initialRotation + rotationAmount * progress;

      leaf.style.top = `${currentY}px`;
      leaf.style.left = `${currentX}px`;
      leaf.style.transform = `rotate(${currentRotation}deg) scale(${1 - progress * 0.1})`; // Slightly less scaling

      // Opacity: Fade in, then fade out (fade out starts a bit later)
      if (progress < 0.1) { 
        leaf.style.opacity = `${progress * 10}`;
      } else if (progress > 0.75) { // Start fading out from 75% progress
        leaf.style.opacity = `${1 - (progress - 0.75) / 0.25}`;
      } else {
        leaf.style.opacity = '1';
      }

      if (progress < 1) {
        requestAnimationFrame(animate);
      } else {
        leaf.remove();
      }
    }
    requestAnimationFrame(animate);
  }

  // Create initial leaves and then set an interval
  for (let i = 0; i < 1; i++) { // Start with just 1 leaf
    setTimeout(createLeaf, Math.random() * 2000); // Random initial delay
  }
  setInterval(createLeaf, newLeafInterval + Math.random() * 1000 - 500); // Spawn new ones less frequently

  // console.log('【简单绿叶动画】更新：方向右上方到左下方，数量减少。');
});

// --- Butterfly and Sun Animations ---
document.addEventListener('DOMContentLoaded', function() {
  // console.log('【蝴蝶与太阳动画】初始化...');

  // Butterfly Animation - Create container if it doesn't exist
  let butterflySanctuary = document.getElementById('butterfly-sanctuary');
  if (!butterflySanctuary) {
    // console.log('Creating butterfly sanctuary container...');
    butterflySanctuary = document.createElement('div');
    butterflySanctuary.id = 'butterfly-sanctuary';
    document.body.appendChild(butterflySanctuary);
  }
  
  // Clear any existing butterflies from previous loads
  butterflySanctuary.innerHTML = '';
  
  // Create butterflies with randomized starting positions and nested structure
  const createButterfly = (index) => {
    const butterflyOuter = document.createElement('div');
    butterflyOuter.classList.add('butterfly'); // General class for positioning behavior

    const butterflyWings = document.createElement('div');
    butterflyWings.classList.add('butterfly-wings'); // For SVG and flutter

    // Assign specific class (b1 or b2) for path animation and specific SVG
    if (index === 0) {
      butterflyOuter.classList.add('b1');
    } else if (index === 1) {
      butterflyOuter.classList.add('b2');
    }
    
    // Set initial top position on the OUTER div
    let verticalPosition;
    if (index === 0) {
      verticalPosition = 15 + Math.random() * 15; // b1: 15-30vh
    } else if (index === 1) {
      verticalPosition = 45 + Math.random() * 20; // b2: 45-65vh
    }
    butterflyOuter.style.top = `${verticalPosition}vh`;
    
    // Set animation delay on the OUTER div (for path animation)
    // Longer, more varied delays for less frequent/synchronized appearances
    let pathAnimDelay;
    if (index === 0) {
      pathAnimDelay = -Math.random() * 12; // b1 can start up to 12s into its 22s cycle
    } else if (index === 1) {
      pathAnimDelay = -Math.random() * 18; // b2 can start up to 18s into its 25s cycle
    }
    butterflyOuter.style.animationDelay = `${pathAnimDelay}s`;

    // Set animation delay for WINGS (flutter animation)
    const flutterAnimDelay = -0.05 - Math.random() * 0.3;
    butterflyWings.style.animationDelay = `${flutterAnimDelay}s`;
    
    // Append wings to the outer butterfly div, then return the outer div
    butterflyOuter.appendChild(butterflyWings);
    return butterflyOuter;
  };
  
  // Create 2 butterflies
  for (let i = 0; i < 2; i++) {
    const butterfly = createButterfly(i);
    butterflySanctuary.appendChild(butterfly);
  }

  // Sun Animation (User's current version - using CSS for ray styling)
  const sunContainer = document.getElementById('sun-rays-container');
  if (sunContainer) {
    // Clear any existing sun rays from previous loads if necessary
    // sunContainer.innerHTML = ''; // Optional: if you want to ensure no duplicates if script runs multiple times
    const sunCore = document.createElement('div');
    sunCore.classList.add('sun-core');
    // Check if sunCore already exists to prevent duplicates if script runs multiple times by mistake
    if (!sunContainer.querySelector('.sun-core')) {
        sunContainer.appendChild(sunCore);
    }

    // Create ray elements; CSS will handle their individual styling and animation via :nth-child
    const existingRays = sunContainer.querySelectorAll('.sun-ray').length;
    if (existingRays === 0) { // Only add rays if they don't exist
        for (let i = 0; i < 8; i++) { // Assuming 8 rays as per user's last JS version
            const ray = document.createElement('div');
            ray.classList.add('sun-ray');
            sunContainer.appendChild(ray);
        }
    }
  } else {
    // console.warn('Sun rays container element not found.');
  }
});

// --- Apply fullscreen body class for homepage only ---
document.addEventListener('DOMContentLoaded', function() {
  if (window.location.pathname === '/') {
    document.body.classList.add('body-fullscreen-no-scroll');
  }
});

// 管理员下拉菜单交互 - 简化版
document.addEventListener('DOMContentLoaded', () => {
  setupAdminDropdown('admin-menu-button', 'admin-dropdown-menu');
  setupAdminDropdown('admin-menu-button-fallback', 'admin-dropdown-menu-fallback');
  
  // 设置下拉菜单功能
  function setupAdminDropdown(buttonId, menuId) {
    const menuButton = document.getElementById(buttonId);
    const dropdownMenu = document.getElementById(menuId);
    
    // 如果找不到相关元素，则退出
    if (!menuButton || !dropdownMenu) return;
    
    console.log(`找到管理员菜单: ${buttonId} 和 ${menuId}`);
    
    // 点击按钮时显示/隐藏下拉菜单
    menuButton.addEventListener('click', (e) => {
      e.preventDefault();
      e.stopPropagation();
      
      const isVisible = dropdownMenu.style.display === 'block';
      
      // 隐藏所有其他菜单
      document.querySelectorAll('[id^=admin-dropdown-menu]').forEach(menu => {
        if (menu !== dropdownMenu) {
          menu.style.display = 'none';
        }
      });
      
      if (isVisible) {
        // 如果菜单已显示，则隐藏它
        console.log(`隐藏菜单: ${menuId}`);
        dropdownMenu.style.display = 'none';
        menuButton.setAttribute('aria-expanded', 'false');
      } else {
        // 如果菜单隐藏，则显示它
        console.log(`显示菜单: ${menuId}`);
        
        // 设置样式确保在最上层显示
        dropdownMenu.style.display = 'block';
        dropdownMenu.style.zIndex = '9999';
        dropdownMenu.style.position = 'fixed'; // 使用fixed定位避免被其他元素遮挡
        
        // 计算位置，确保下拉菜单显示在按钮下方
        const buttonRect = menuButton.getBoundingClientRect();
        dropdownMenu.style.top = (buttonRect.bottom + window.scrollY) + 'px';
        dropdownMenu.style.left = (buttonRect.left + window.scrollX) + 'px';
        
        menuButton.setAttribute('aria-expanded', 'true');
      }
    });
  }
  
  // 点击文档其他位置时关闭下拉菜单
  document.addEventListener('click', (e) => {
    if (!e.target.closest('[id^=admin-menu-button]') && !e.target.closest('[id^=admin-dropdown-menu]')) {
      document.querySelectorAll('[id^=admin-dropdown-menu]').forEach(menu => {
        menu.style.display = 'none';
      });
      
      document.querySelectorAll('[id^=admin-menu-button]').forEach(button => {
        button.setAttribute('aria-expanded', 'false');
      });
    }
  });
});

// 在文档加载完成后执行
document.addEventListener("DOMContentLoaded", function() {
  // ... existing code ...
  
  // 处理小太阳的点击逻辑
  const sunLink = document.getElementById('admin-sun-link');
  if (sunLink) {
    // 检查是否已登录
    const isAdmin = document.body.getAttribute('data-is-admin') === 'true';
    
    if (isAdmin) {
      // 已登录状态，点击显示提示
      sunLink.addEventListener('click', function(e) {
        e.preventDefault(); // 阻止默认跳转
        
        // 显示简单提示
        const toast = document.createElement('div');
        toast.className = 'fixed top-20 left-1/2 -translate-x-1/2 bg-gray-700/90 text-white px-4 py-2 rounded-lg shadow-lg z-50';
        toast.textContent = '您已经登录了!';
        document.body.appendChild(toast);
        
        // 3秒后移除提示
        setTimeout(() => {
          toast.style.opacity = '0';
          toast.style.transition = 'opacity 0.5s ease';
          setTimeout(() => document.body.removeChild(toast), 500);
        }, 3000);
      });
    }
    // 未登录状态不需处理，让链接正常跳转
  }
});
